#include <stdio.h>
#include "common.h"

int connectcosts1[4] = { 1,  0,  1, 999 };

static struct distance_table dt1;
static int me;  // 注意！一定要声明为局部变量

void printdt1(dtptr)
struct distance_table *dtptr;

{
    printf("             via   \n");
    printf("   D1 |    0     2 \n");
    printf("  ----|-----------\n");
    printf("     0|  %3d   %3d\n",dtptr->costs[0][0], dtptr->costs[0][2]);
    printf("dest 2|  %3d   %3d\n",dtptr->costs[2][0], dtptr->costs[2][2]);
    printf("     3|  %3d   %3d\n",dtptr->costs[3][0], dtptr->costs[3][2]);

}

/* students to write the following two routines, and maybe some others */


void rtinit1()
{
    me = 1;
    printf("Initialize dt%d\n", me);
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            dt1.costs[i][j] = 999;
        }
    }
    dt1.costs[1][1] = 0;
    dt1.costs[1][2] = 1;
    dt1.costs[1][0] = 1;
    printTable(&dt1, me);

    send2Neighbors(&dt1, me);
}


void rtupdate1(rcvdpkt)
  struct rtpkt *rcvdpkt;
  
{
    int src = rcvdpkt->sourceid;
    for (int i = 0; i < 4; ++i) {
        dt1.costs[src][i] = rcvdpkt->mincost[i];
    }
    int needNotify = 0;
    for (int i = 0; i < 4; ++i) {
        if (i == me)
            continue;
        int minDist = 999;  // compute me -> i
        for (int j = 0; j < 4; ++j) { // via j
            if (dt1.costs[j][i] == 999) {
                continue;
            }
            minDist = min(minDist, dt1.costs[me][j] + dt1.costs[j][i]);
        }
        if (minDist < dt1.costs[me][i]) {
            dt1.costs[me][i] = minDist;
            // update the Dx(y) to neighbors
            needNotify = 1;
        }
    }

    if (needNotify) {
        printf("dt%d Updated:\n", me);
        send2Neighbors(&dt1, me);
    }
    printTable(&dt1, me);
}


void linkhandler1(linkid, newcost)
int linkid, newcost;   
/* called when cost from 1 to linkid changes from current value to newcost*/
/* You can leave this routine empty if you're an undergrad. If you want */
/* to use this routine, you'll need to change the value of the LINKCHANGE */
/* constant definition in prog3.c from 0 to 1 */
	
{
}


